package com.lovo.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.Application;
import com.lovo.config.ApplicationConfig;
import com.lovo.model.InvoiceDO;
import com.lovo.service.InvoiceService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class InvoiceServlet extends HttpServlet {

    private InvoiceService invoiceService;
    private ObjectMapper objectMapper;

    @Override
    public void init() throws ServletException {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);
        this.invoiceService = (InvoiceService) context.getBean("invoiceService");
        this.objectMapper = (ObjectMapper) context.getBean("objectMapper");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List invoiceList = this.invoiceService.find();
        resp.getWriter().print(this.objectMapper.writeValueAsString(invoiceList));

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        int amount = Integer.parseInt(req.getParameter("amount"));
        this.invoiceService.create(userId,amount);
        resp.getWriter().print("添加成功");

    }
}
